Date: March 3rd, 2020
Author: Bryan Rosales
Program: Intro to Machine Learning with TensorFlow
Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
# Python libraries to use in this project
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import time
import tensorflow as tf
import numpy as np
import pandas as pd
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
import json
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow_hub as hub
from workspace_utils import active_session
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
# Display Tensorflow and Keras versions
print('Using:')
print('\t\u2022 TensorFlow version:', tf.__version__)
print('\t\u2022 tf.keras version:', tf.keras.__version__)
print('\t\u2022 Running on GPU' if tf.test.is_gpu_available() else '\t\u2022 GPU device not found. Running on CPU')
# By default GPU workspace is disable, but once the network is built, I will use the GPU power to train it.
Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.
# TODO: Load the dataset with TensorFlow Datasets.
splits = ['train','test','validation']
dataset, dataset_info = tfds.load('oxford_flowers102', split=splits, as_supervised=True, with_info=True)
# TODO: Create a training set, a validation set and a test set.
(training_set, testing_set, validation_set) = dataset
# TODO: Get the number of examples in each set from the dataset info.
training_examples = dataset_info.splits['train'].num_examples
testing_examples = dataset_info.splits['test'].num_examples
validation_examples = dataset_info.splits['validation'].num_examples
print('Training Examples: {:,}'.format(training_examples))
print('Testing Examples: {:,}'.format(testing_examples))
print('Validation Examples: {:,}'.format(validation_examples))
# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes
print('\nNumber of Classes: {:,}'.format(num_classes))
# Dataset Metadata
dataset_info
# TODO: Print the shape and corresponding label of 3 images in the training set.
# Creates a plot with 1 row and 3 columns
fig, (ax1,ax2,ax3) = plt.subplots(figsize=(18,15) ,ncols=3 )
image1 = []
label1 = []
for image,label in training_set.take(3):
image = image.numpy()
label = label.numpy()
image1.append(image)
label1.append(label)
ax1.imshow(image1[0])
ax1.set_title('Class: ' + str(label1[0]) + ', Shape: ' + str(np.array(image1[0]).shape))
ax2.imshow(image1[1])
ax2.set_title('Class: ' + str(label1[1]) + ', Shape: ' + str(np.array(image1[1]).shape))
ax3.imshow(image1[2])
ax3.set_title('Class: ' + str(label1[2]) + ', Shape: ' + str(np.array(image1[2]).shape))
# Images contain different shapes
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding image label.
for image,label in training_set.take(25):
imgtf = image
image = image.numpy()
label = label.numpy()
plt.title('Class: ' + str(label))
plt.imshow(image)
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
with open('label_map.json', 'r') as f:
class_names = json.load(f)
print('Number of Classes',len(class_names))
# Print the Class_name Dictionary
# for i in sorted (class_names.keys()) :
# print(i,class_names[i])
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding class name.
for image,label in training_set.take(8):
image = image.numpy()
label = label.numpy()
plt.title('Class: ' + str(label) + ", Class_Name: " + class_names[str(label+1)])
plt.imshow(image)
Since the images have different sizes, it is require to resize every image to (224, 224, 3) before training the network. The next is an example of original image vs a resized image.
IMAGE_SIZE = 224
#The function applies some transformations on the image to help out with Network Training and generalizing of the model
#At least one of the transformation below will be applied.
def image_augmentation(img, label):
x = np.random.randint(0, 4)
# print('random: ',x)
# Cases to apply transformations
if x == 0:
img = tf.image.rot90(img, k=np.random.randint(1, 4))
elif x == 1:
img = tf.image.random_flip_up_down(img)
img = tf.image.random_flip_left_right(img, 42)
elif x == 2:
img = tf.image.random_hue(img, 0.08)
img = tf.image.random_saturation(img, 0.6, 1.6)
img = tf.image.random_brightness(img, 0.05)
img = tf.image.random_contrast(img, 0.7, 1.3)
img, label = image_preprocessing(img, label)
return img, label
# This function resizes the image to (224, 224, 3) and converts it to float32 and normalize the values between 0 and 1
def image_preprocessing(img, label):
img = tf.image.resize(img, [IMAGE_SIZE, IMAGE_SIZE], method= tf.image.ResizeMethod.NEAREST_NEIGHBOR)
img = tf.image.convert_image_dtype(img, dtype=tf.float32)
return img, label
for image,label in training_set.take(1):
label = label.numpy()
image = image.numpy()
new_image, label = image_preprocessing(image, label)
fig, (ax1,ax2) = plt.subplots(figsize=(15,10) , ncols=2)
ax1.imshow(image)
ax1.set_title('Original Image ' + str(image.shape) + ', Class_Name: ' + class_names[str(label+1)])
ax2.imshow(new_image)
ax2.set_title('Resized Image ' + str(new_image.shape) + ', Class_Name: ' + class_names[str(label+1)])
print('Org Img: ', image.shape)
print('New Img: ', new_image.shape)
image_augmentation()¶The following code compare images after preprocessing and transformation (original vs. transformed).
fig = plt.figure(figsize= (12, 25))
n=1
rows = 4
cols = 2
for image,label in training_set.take(4):
image1, label1 = image_augmentation(image, label)
label = label.numpy()
label1 = label1.numpy()
# Plot Original Image
fig.add_subplot(rows, cols, n)
plt.imshow(image)
plt.title('Original, Class: ' + class_names[str(label+1)] + ', Shape:' + str(tf.shape(image).numpy()))
n+=1
# Plot transformed Image
fig.add_subplot(rows, cols, n)
plt.imshow(image1)
plt.title('Transformed, Class: ' + class_names[str(label1+1)] + ', Shape:' + str(tf.shape(image1).numpy()))
n+=1
Since our training set only contains 1,020 images, I will use the function image_augmentation() to make some transformations to the images in order to augment the dataset and help our network out to generalize the data correctly.
# In order to fit the data to the model, it is necessary to create a pipeline keeping in mind processing times of the operations I am performing on the images. In this case, I am using batches 64 images.
batch_size = 64
training_batches = training_set.shuffle(training_examples//4).map(image_augmentation).batch(batch_size).prefetch(1)
validation_batches = validation_set.map(image_preprocessing).batch(batch_size).prefetch(1)
testing_batches = testing_set.map(image_preprocessing).batch(batch_size).prefetch(1)
Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!
When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.
Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.
# Model chosen is MobileNet v2.0 features vector
URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
pretrained_model = hub.KerasLayer(URL, trainable=False, input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))
# pretrained_model = tf.keras.applications.MobileNetV2(input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3), include_top = False,
# weights='imagenet', alpha=1.4)
# pretrained_model.trainable = False
# Model Arquitecture
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.Dense(1024, activation='relu'),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(102, activation='softmax')
])
model.summary()
# Model Optimization
model.compile(
optimizer= 'adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Model Evaluation before Training
loss, accuracy = model.evaluate(testing_batches)
EPOCHS = 10
early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = 3)
best_model = tf.keras.callbacks.ModelCheckpoint('./models/best_model.h5', monitor='val_loss', save_best_only=True)
# Define the Keras TensorBoard callback.
#log_dir = "./logs/fit/"
#tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir)
#with active_session():
history = model.fit(training_batches,
epochs=EPOCHS,
validation_data=validation_batches,
callbacks=[best_model])
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']
training_loss = history.history['loss']
validation_loss = history.history['val_loss']
epochs_range=range(EPOCHS)
# print(epochs_range)
plt.figure(figsize=(15, 5))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower left')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
# TODO: Print the loss and accuracy values achieved on the entire test set.
# Model Evaluation before Training
new_loss, new_accuracy = model.evaluate(testing_batches)
Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).
model_filepath = './models'
tf.saved_model.save(model, model_filepath)
Load the Keras model you saved above.
# Load the Keras model saved previously
model_filepath = './models'
reloaded_model = tf.keras.models.load_model(model_filepath)
reloaded_model.summary()
Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.
The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).
First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.
Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.
Finally, convert your image back to a NumPy array using the .numpy() method.
To check your process_image function we have provided 4 images in the ./test_images/ folder:
The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.
from PIL import Image
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)
test_image = tf.convert_to_tensor(test_image)
processed_test_image, label = image_preprocessing(test_image, 0)
fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()
Once you can get images in the correct format, it's time to write the predict function for making inference with your model.
Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.
# TODO: Create the predict function
def predict(image_path, model, top_k):
img = np.asarray(Image.open(image_path))
img = tf.convert_to_tensor(img)
img, label = image_preprocessing(img, 0)
img_batch = tf.reshape(img, [1, IMAGE_SIZE, IMAGE_SIZE, 3])
probs = model.predict(img_batch)
probs = probs.flatten()
ps, classes = tf.math.top_k(probs, k=top_k, sorted=True)
ps = ps.numpy()
classes = classes.numpy()
return ps, classes, img
# Testing Predict() function
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
ps, classes, img = predict(image_path, reloaded_model, 5)
print(ps, type(ps[0]))
print(classes, type(classes[0]))
It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:
In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.
# TODO: Plot the input image along with the top 5 classes
import os
TOP_K = 5
dir_path = './test_images/'
for img_filename in os.listdir(dir_path):
ps, classes, img = predict(dir_path + img_filename, reloaded_model, TOP_K)
labels =[]
for l in classes:
labels.append(class_names[str(l+1)])
fig, (ax1, ax2) = plt.subplots(figsize=(10,9), ncols=2)
ax1.imshow(img)
ax1.axis('off')
ax1.set_title(img_filename)
ax2.barh(np.arange(TOP_K), ps)
ax2.set_aspect(0.1)
ax2.set_yticks(np.arange(TOP_K))
ax2.set_yticklabels(labels, size='small');
ax2.set_title('Class Probability')
ax2.set_xlim(0, 1.1)
plt.tight_layout()